from django.db import models
from django.contrib.auth.models import User
from django.utils import timezone

class Category(models.Model):
    """书籍分类"""
    name = models.CharField(max_length=100, verbose_name="分类名称")
    description = models.TextField(blank=True, verbose_name="分类描述")
    created_at = models.DateTimeField(auto_now_add=True, verbose_name="创建时间")
    
    class Meta:
        verbose_name = "书籍分类"
        verbose_name_plural = "书籍分类"
    
    def __str__(self):
        return self.name

class Book(models.Model):
    """书籍模型"""
    STATUS_CHOICES = [
        ('available', '可借阅'),
        ('borrowed', '已借出'),
        ('reserved', '已预约'),
        ('maintenance', '维护中'),
    ]
    
    isbn = models.CharField(max_length=20, unique=True, verbose_name="ISBN编号")
    title = models.CharField(max_length=200, verbose_name="书名")
    author = models.CharField(max_length=100, verbose_name="作者")
    category = models.ForeignKey(Category, on_delete=models.CASCADE, verbose_name="分类")
    publisher = models.CharField(max_length=100, blank=True, verbose_name="出版社")
    publish_date = models.DateField(null=True, blank=True, verbose_name="出版日期")
    description = models.TextField(blank=True, verbose_name="简介")
    status = models.CharField(max_length=20, choices=STATUS_CHOICES, default='available', verbose_name="状态")
    total_copies = models.PositiveIntegerField(default=1, verbose_name="总数量")
    available_copies = models.PositiveIntegerField(default=1, verbose_name="可借数量")
    location = models.CharField(max_length=50, blank=True, verbose_name="存放位置")
    created_at = models.DateTimeField(auto_now_add=True, verbose_name="添加时间")
    updated_at = models.DateTimeField(auto_now=True, verbose_name="更新时间")
    
    class Meta:
        verbose_name = "书籍"
        verbose_name_plural = "书籍"
        ordering = ['-created_at']
    
    def __str__(self):
        return f"{self.title} - {self.author}"
    
    def save(self, *args, **kwargs):
        if not self.pk:  # 新创建的书籍
            self.available_copies = self.total_copies
        super().save(*args, **kwargs)

class BorrowRecord(models.Model):
    """借阅记录"""
    STATUS_CHOICES = [
        ('borrowed', '已借出'),
        ('returned', '已归还'),
        ('overdue', '已逾期'),
    ]
    
    book = models.ForeignKey(Book, on_delete=models.CASCADE, verbose_name="书籍")
    borrower = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name="借阅者")
    borrow_date = models.DateTimeField(default=timezone.now, verbose_name="借阅日期")
    due_date = models.DateTimeField(verbose_name="应还日期")
    return_date = models.DateTimeField(null=True, blank=True, verbose_name="实际归还日期")
    status = models.CharField(max_length=20, choices=STATUS_CHOICES, default='borrowed', verbose_name="状态")
    notes = models.TextField(blank=True, verbose_name="备注")
    
    class Meta:
        verbose_name = "借阅记录"
        verbose_name_plural = "借阅记录"
        ordering = ['-borrow_date']
    
    def __str__(self):
        return f"{self.borrower.username} - {self.book.title}"
    
    def is_overdue(self):
        """检查是否逾期"""
        if self.status == 'borrowed' and timezone.now() > self.due_date:
            return True
        return False
    
    def save(self, *args, **kwargs):
        # 如果是新创建的借阅记录
        if not self.pk:
            # 减少可借数量
            self.book.available_copies -= 1
            self.book.save()
        super().save(*args, **kwargs)

class Reservation(models.Model):
    """预约记录"""
    STATUS_CHOICES = [
        ('pending', '等待中'),
        ('fulfilled', '已满足'),
        ('cancelled', '已取消'),
    ]
    
    book = models.ForeignKey(Book, on_delete=models.CASCADE, verbose_name="书籍")
    user = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name="预约者")
    reservation_date = models.DateTimeField(default=timezone.now, verbose_name="预约日期")
    status = models.CharField(max_length=20, choices=STATUS_CHOICES, default='pending', verbose_name="状态")
    notes = models.TextField(blank=True, verbose_name="备注")
    
    class Meta:
        verbose_name = "预约记录"
        verbose_name_plural = "预约记录"
        ordering = ['-reservation_date']
    
    def __str__(self):
        return f"{self.user.username} - {self.book.title}"
